import os
import re
from src.utils.global_variable import logging
from openpyxl import Workbook
from src.utils.global_variable import Var

var = Var()

readme_paths = []  # 所有readme文件路径信息 {topic: path}
hyper_dic = {}  # 所有topic下的链接信息 {topic: {hyper_title: link}}


# def get_topic(path):
#     """
#     获取所有topic路径
#     :param path: markdown路径
#     :return: 所有topic信息 {topic: path}
#     """
#     markdown_path = path
#     for file in os.listdir():
#         if '_bookmap_' in file:
#             bookmap_path = markdown_path + '\\' + file
#
#             with open(bookmap_path, 'r', encoding='utf-8') as f:
#                 line = f.read()
#                 pattern = r'\[(?P<title>.*?)\]\((?P<path>.*?\.md)\)'
#                 i_list = re.finditer(pattern=pattern, string=line)
#
#                 for i in i_list:
#                     title_dic[i.group('title')] = markdown_path + '\\' + i.group('path')
#                     logging.info(f'{i.group("title")}: {i.group("path")}')
#             break


def get_readme_path(dir_path):
    """获取路径下所有readme路径"""
    for root, dirs, files in os.walk(dir_path):
        for file in files:
            if file.lower() == 'readme.md' or file.lower() == 'readme.en.md':
                readme_paths.append(os.path.join(root, file))
                logging.info(f'{file} path: {os.path.join(root, file)}')


def get_readme_hyperlink(queue):
    """获取readme文件中的超链接{path：{hyper_title: link}}"""
    for readme_path in readme_paths:
        try:
            with open(readme_path, 'r', encoding='utf-8') as f:
                text = f.read()
                pattern = r'\[(?P<hyper_title>.*?)\]\((?P<link>.*?)\)'
                i_list = re.finditer(pattern=pattern, string=text)
                for i in i_list:
                    if i.group('hyper_title') == '':
                        continue
                    if not i.group('link').startswith('http'):
                        if '.md' not in i.group('link') and '#' not in i.group('link'):
                            continue

                    if i.group('link').startswith('figures') or i.group(
                            'link').startswith('public_sys-resources'):
                        continue
                    queue.put(
                        ''.join([readme_path, i.group('hyper_title'), i.group('link')]))
                    link = i.group('link')
                    if link.startswith('#'):
                        link = readme_path.split("\\")[-1] + link
                    if hyper_dic.get(readme_path):
                        hyper_dic[readme_path].append((i.group('hyper_title'), link))
                    else:
                        hyper_dic[readme_path] = [(i.group('hyper_title'), link)]

                pattern2 = r'<a\s+href="([^"]*)"[^>]*>([^<]*)</a>'
                matches = re.finditer(pattern=pattern2, string=text)
                for match in matches:
                    link = match.group(1)
                    hyper_title = match.group(2)
                    queue.put(''.join([readme_path, hyper_title, link]))
                    if hyper_dic.get(readme_path):
                        hyper_dic[readme_path].append((hyper_title, link))
                    else:
                        hyper_dic[readme_path] = [(hyper_title, link)]
        except FileNotFoundError as e:
            queue.put(f'{readme_path}文件不存在，原因：{e}')


# def get_hyperlink(queue):
#     """
#     获取所有topic下的链接信息 {topic: {hyper_title: link}}
#     :return:
#     """
#     for faq_markdown_path in title_dic.values():
#         try:
#             with open(faq_markdown_path, 'r', encoding='utf-8') as f:
#                 text = f.read()
#                 pattern = r'\[(?P<hyper_title>.*?)\]\((?P<link>.*?)\)'
#                 i_list = re.finditer(pattern=pattern, string=text)
#
#                 for i in i_list:
#                     if i.group('hyper_title') == '':
#                         continue
#                     if not i.group('link').startswith('http'):
#                         if '.md' not in i.group('link') and '#' not in i.group('link'):
#                             continue
#
#                     if i.group('link').startswith('figures') or i.group(
#                             'link').startswith('public_sys-resources'):
#                         continue
#                     queue.put(
#                         ''.join([faq_markdown_path.split("\\")[-1][:-3], i.group('hyper_title'), i.group('link')]))
#                     link = i.group('link')
#                     if link.startswith('#'):
#                         link = faq_markdown_path.split("\\")[-1] + link
#                     if hyper_dic.get(faq_markdown_path.split("\\")[-1][:-3]):
#                         hyper_dic[faq_markdown_path.split("\\")[-1][:-3]].append((i.group('hyper_title'), link))
#                     else:
#                         hyper_dic[faq_markdown_path.split("\\")[-1][:-3]] = [(i.group('hyper_title'), link)]
#
#                 pattern2 = r'<a\s+href="([^"]*)"[^>]*>([^<]*)</a>'
#                 matches = re.finditer(pattern=pattern2, string=text)
#                 for match in matches:
#                     link = match.group(1)
#                     hyper_title = match.group(2)
#                     queue.put(''.join([faq_markdown_path.split("\\")[-1][:-3], hyper_title, link]))
#                     if hyper_dic.get(faq_markdown_path.split("\\")[-1][:-3]):
#                         hyper_dic[faq_markdown_path.split("\\")[-1][:-3]].append((hyper_title, link))
#                     else:
#                         hyper_dic[faq_markdown_path.split("\\")[-1][:-3]] = [(hyper_title, link)]
#         except FileNotFoundError as e:
#             queue.put(f'{faq_markdown_path}文件不存在，原因：{e}')


def write_to_excel():
    """
    将获取到的hyper信息写入导表格中
    :return:
    """
    wb = Workbook()
    ws = wb.active
    ws.append(['路径', '链接信息', '链接地址'])

    for key, value in hyper_dic.items():
        for v in value:
            ws.append([key, v[0], v[1]])

    wb.save('超链接.xlsx')


def main(dir_path, queue):
    """
    主函数
    :return:
    """
    to_be_check_dir = dir_path
    os.chdir(to_be_check_dir)

    get_readme_path(to_be_check_dir)
    get_readme_hyperlink(queue)
    write_to_excel()
    var.excel_path = dir_path + r'\超链接.xlsx'
    return var.excel_path


if __name__ == '__main__':
    pass
